# HomeBox Build Script
Write-Host "Building HomeBox..."

# Check dependencies
Write-Host "Checking dependencies..."
$pnpm = Get-Command pnpm -ErrorAction SilentlyContinue
if (-not $pnpm) {
    Write-Host "❌ pnpm is not installed" -ForegroundColor Red
    pause
    exit 1
}

$go = Get-Command go -ErrorAction SilentlyContinue
if (-not $go) {
    Write-Host "❌ Go is not installed" -ForegroundColor Red
    pause
    exit 1
}

Write-Host "✅ Dependencies check passed" -ForegroundColor Green

# Build frontend
Write-Host "Building frontend..."
Set-Location frontend
& pnpm install
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ Failed to install frontend dependencies" -ForegroundColor Red
    pause
    exit 1
}

& pnpm run build
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ Frontend build failed" -ForegroundColor Red
    pause
    exit 1
}

Set-Location ..

# Copy frontend assets
Write-Host "Copying frontend assets..."
$publicDir = "backend\app\api\static\public"
if (Test-Path $publicDir) {
    Remove-Item -Recurse -Force $publicDir
}

New-Item -ItemType Directory -Path $publicDir | Out-Null

Copy-Item -Recurse -Force "frontend\.output\public\*" $publicDir
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ Failed to copy frontend assets" -ForegroundColor Red
    pause
    exit 1
}

# Build backend
Write-Host "Building backend..."
Set-Location backend
Write-Host "Current directory: $PSScriptRoot"
Write-Host "Building with command: go build -ldflags=\"-s -w\" -tags \"osusergo netgo static_build\" -o ..\homebox.exe .\app\api"
& go build -ldflags="-s -w" -tags "osusergo netgo static_build" -o ..\homebox.exe .\app\api
if ($LASTEXITCODE -ne 0) {
    Write-Host "❌ Backend build failed" -ForegroundColor Red
    pause
    exit 1
}

Set-Location ..

# Verify executable was created
if (Test-Path "homebox.exe") {
    Write-Host "✅ homebox.exe was created successfully!" -ForegroundColor Green
    Get-Item "homebox.exe" | Format-List
} else {
    Write-Host "❌ homebox.exe was not created" -ForegroundColor Red
}

Write-Host "✅ Build process completed!" -ForegroundColor Green

pause